package cn.consult.controller.sys.pay;

import cn.consult.sys.entity.TWeEquipment;
import cn.consult.sys.entity.T_WeInfo;
import cn.consult.sys.service.TWeEquipmentService;
import cn.consult.sys.service.T_WeInfoService;
import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 15196
 * @ Author：周xx
 * @ Date：2024-04-17-14:06
 * @ Version：1.0
 * @ Description：
 */
@RestController
@RequestMapping("/alipay")
public class PayController {

    //支付宝沙箱网关地址
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Autowired
    AliPayConfig aliPayConfig;

    @Autowired
    TWeEquipmentService tWeEquipmentService;
    @Autowired
    T_WeInfoService tWeInfoService;

    @GetMapping("/pay")
    public void pay(String number, String payType, BigDecimal money, HttpServletResponse response) throws Exception {
        //前端传设备设备名称  金额  支付方式即可
        LambdaQueryWrapper<TWeEquipment> equipmentLambdaQueryWrapper = new LambdaQueryWrapper<>();
        equipmentLambdaQueryWrapper.eq(TWeEquipment::getEquipmentNumber, number);
        TWeEquipment tWeEquipment = tWeEquipmentService.list(equipmentLambdaQueryWrapper).get(0);

//1.创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayclient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublickey(), SIGN_TYPE);
//2，创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest(); // 发送请求的 Request类
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        JSONObject bizContent = new JSONObject();
        String orderNO = UUID.randomUUID().toString().replace("-", "") + new Date().getTime();
        bizContent.set("out_trade_no", orderNO); // 我们自己生成的订单编号
        bizContent.set("total_amount", money);// 订单的总金额
        bizContent.set("subject", tWeEquipment.getEquipmentNumber());// 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY"); // 固定配置
        request.setBizContent(bizContent.toString());
        request.setReturnUrl("http://localhost:10003/system/apartment/werecord1");//支付完成跳转的路径
        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayclient.pageExecute(request).getBody();// 调用SDK生成表单

            //插入支付记录
            T_WeInfo t_weInfo = new T_WeInfo();
            t_weInfo.setSerialNumber(orderNO);
            t_weInfo.setRoomNumber(tWeEquipment.getEquipmentNumber());
            t_weInfo.setResidentName(tWeEquipment.getEquipmentAddress());
            t_weInfo.setRechargeTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            t_weInfo.setRechargeBeforeMoney(tWeEquipment.getEquipmentResidueMoney());
            t_weInfo.setRechargeMoney(new Double(String.valueOf(money)));
            Double v = new Double(String.valueOf(money));
            Double equipmentResidueMoney = tWeEquipment.getEquipmentResidueMoney();
            double v1 = equipmentResidueMoney + v;
            t_weInfo.setMoney(v1);
            t_weInfo.setRechargeType("支付宝");
            tWeInfoService.save(t_weInfo);


            TWeEquipment tWeEquipment1 = new TWeEquipment();
            tWeEquipment1.setId(tWeEquipment.getId());
            tWeEquipment1.setEquipmentResidueMoney(v1);
            int i = (int) v1;
            int a = i / 1;
            tWeEquipment1.setEquipmentResidueNumber(a);
            tWeEquipmentService.updateById(tWeEquipment1);


        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + CHARSET);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }


    @PostMapping("/notify")
    public void notify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                String sign = params.get("sign");
                String content = AlipaySignature.getSignCheckContentV1(params);
            }
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            boolean b = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublickey(), "UTF-8");
            if (b) {
                System.out.println("=========异步回调验签成功========");
                // 验签通过
                System.out.println("交易名称:" + params.get("subject"));
                System.out.println("交易状态:" + params.get("trade_status"));
                System.out.println("支付宝交易凭证号:" + params.get("trade_no"));
                System.out.println("商户订单号:" + params.get("out_trade_no"));
                System.out.println("交易金额:" + params.get("total_amount"));
                System.out.println("买家在支付宝唯-id: " + params.get("buyer_id"));
                System.out.println("买家付款时间:" + params.get("gmt_payment"));
                System.out.println("买家付款金额:" + params.get("buyer_pay_amdunt"));

                String tradeNo = params.get("out_trade_no");
                String gmtPayment = params.get("gmt_payment");
                String alipayTradeNo = params.get("trade_no");
                //更新订单状态为已支付，设置支付信息
//                orders orders =ordersService.selectBy0rderNo(tradeNo);
//                orders.setStatus("已支付");
//                orders.setPayTime(gmtPayment);
//                orders.setPayNo(alipayTradeNo);
//                ordersService.updateById(orders):
            }
        }
    }
}
